var ajaxUrl = require('../../utils/url.js');
var encrypt = require('../../utils/encrypt.js');
const app = getApp()
Page({
  data: {
    goodsId: 0,
    productInfo: {}
  },
  onLoad: function( option ) {
    this.setData({
      goodsId: option.id
    });
    this.fetchData()
  },
  fetchData () {
    const self = this
    wx.request({
      method: "POST",
      url: ajaxUrl.goodsList(),
      data: {goodsId: self.data.goodsId},
      success: function(res){
        if(res.data.code === 200){
          self.setData({
            productInfo: res.data.data
          })
        }else{
          console.error(res.data.msg)
        }
      }
    })
  },
  addCart () {
    const self = this
    let params = {
      token: app.globalData.token
    }
    let cartParams=[]
    let obj = {
      cnt: 1,
      goodsId: self.data.goodsId
    }
    wx.request({
      method: "POST",
      url: ajaxUrl.cartsList(),
      data: params,
      success: function(res){
        if(res.data.code === 200){
          let cntflag = false
          res.data.data.forEach(function(item){
            if(item.goodsId === self.data.goodsId){
              item.cartCnt++
              cntflag = true
            }
            cartParams.push({cnt:item.cartCnt, goodsId:  parseInt(item.goodsId)})
          })
          if(!cntflag){
            cartParams.push(obj)
          }
          self.mergeCountwithtoken(cartParams)
        }
      }
    })
  },
  _objIsInArray(obj,arr){
    let tmpStatus=false;
    for(let j=0;j<arr.length;j++){
      if(obj.goodsId==arr[j].goodsId){
        return j;
        break;
      }else{
        tmpStatus=false;
      }
    }
    if(!tmpStatus){
      return -1;
    }
  },
  mergeCountwithtoken (obj) {
    const self = this
    let newArr=[]
    for(let i=0;i<obj.length;i++){
      let index= self._objIsInArray(obj[i],newArr)
      if(index !==-1){
        obj[index].cnt++
      } else {
        newArr.push(obj[i])
      }
    }
    newArr = encrypt.encrypt(newArr)
    wx.request({
      method: "POST",
      url: ajaxUrl.addToCart(),
      data: newArr,
      success: function(res){
        if(res.data.code === 200){
          wx.showToast({
            title:'添加购物车成功'
          })
        }else{
          console.error(res.data.msg)
        }
      }
    })
  },
  buy () {
    const self = this
    let params = []
    self.data.productInfo.cartCnt = 1
    params.push(self.data.productInfo)
    self.setProductinfoToSession(params)
    
    wx.navigateTo({
      url: '../order/comfire/comfire?id=' + self.data.goodsId
    });
  },
  setProductinfoToSession (obj) {
    // window.sessionStorage.setItem('goodsInfo',params)
    wx.setStorage({
      key:"goodsInfo",
      data: obj
    })
  }
});